<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="undo log的作用为了保证事务的原子性，InnoDB引入了undo日志，undo日志记载了回滚操作所需的内容。 undo是逻辑日志，只是将数据库逻辑地恢复到原来的样子；所有修改都被逻辑地取消了，但是数据结构和页本身在回滚之后可能不大相同。 undo log有两个作用：提供回滚和**多版本并发控制(MVCC)**。 事务id在事务在对表中的记录进行修改的时候，会为这个事务分配一个唯一的事务id，">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL —— Undo log">
<meta property="og:url" content="http://example.com/2021/12/09/undolog/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="undo log的作用为了保证事务的原子性，InnoDB引入了undo日志，undo日志记载了回滚操作所需的内容。 undo是逻辑日志，只是将数据库逻辑地恢复到原来的样子；所有修改都被逻辑地取消了，但是数据结构和页本身在回滚之后可能不大相同。 undo log有两个作用：提供回滚和**多版本并发控制(MVCC)**。 事务id在事务在对表中的记录进行修改的时候，会为这个事务分配一个唯一的事务id，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/2021/12/09/undolog/undolog.png">
<meta property="article:published_time" content="2021-12-09T10:47:10.000Z">
<meta property="article:modified_time" content="2021-12-10T17:53:31.026Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2021/12/09/undolog/undolog.png">


<link rel="canonical" href="http://example.com/2021/12/09/undolog/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/12/09/undolog/","path":"2021/12/09/undolog/","title":"MySQL —— Undo log"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>MySQL —— Undo log | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#undo-log%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">undo log的作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8B%E5%8A%A1id"><span class="nav-number">2.</span> <span class="nav-text">事务id</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%90%84%E7%A7%8D%E7%B1%BB%E5%9E%8B%E7%9A%84Undo-log"><span class="nav-number">3.</span> <span class="nav-text">各种类型的Undo log</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Undo-log-%E7%9A%84%E7%AE%A1%E7%90%86"><span class="nav-number">4.</span> <span class="nav-text">Undo log 的管理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#undo%E5%8F%8Aredo%E5%A6%82%E4%BD%95%E8%AE%B0%E5%BD%95%E4%BA%8B%E5%8A%A1"><span class="nav-number">5.</span> <span class="nav-text">undo及redo如何记录事务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Undo-Redo%E4%BA%8B%E5%8A%A1%E7%9A%84%E7%AE%80%E5%8C%96%E8%BF%87%E7%A8%8B"><span class="nav-number">5.1.</span> <span class="nav-text">Undo + Redo事务的简化过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B4%A9%E6%BA%83%E6%81%A2%E5%A4%8D"><span class="nav-number">5.2.</span> <span class="nav-text">崩溃恢复</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/12/09/undolog/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="MySQL —— Undo log | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MySQL —— Undo log
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-12-09 18:47:10" itemprop="dateCreated datePublished" datetime="2021-12-09T18:47:10+08:00">2021-12-09</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-12-11 01:53:31" itemprop="dateModified" datetime="2021-12-11T01:53:31+08:00">2021-12-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/MySQL/" itemprop="url" rel="index"><span itemprop="name">MySQL</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="undo-log的作用"><a href="#undo-log的作用" class="headerlink" title="undo log的作用"></a>undo log的作用</h2><p>为了保证事务的原子性，InnoDB引入了undo日志，undo日志记载了回滚操作所需的内容。</p>
<p>undo是<strong>逻辑日志</strong>，只是将数据库逻辑地恢复到原来的样子；所有修改都被逻辑地取消了，但是数据结构和页本身在回滚之后可能不大相同。</p>
<p>undo log有两个作用：<strong>提供回滚</strong>和**多版本并发控制(MVCC)**。</p>
<h2 id="事务id"><a href="#事务id" class="headerlink" title="事务id"></a>事务id</h2><p>在事务在对表中的记录进行修改的时候，会为这个事务分配一个唯一的事务id，这个事务id是递增的，所以事务id越小越先执行。未被分配事务id的事务的id默认是0。</p>
<h2 id="各种类型的Undo-log"><a href="#各种类型的Undo-log" class="headerlink" title="各种类型的Undo log"></a>各种类型的Undo log</h2><p>InnoDB对不同场景的设计了不同类型的undo日志，比如TRX_UNDO_INSERT_REC, TRX_UNDO_DEL_MARK_REC.</p>
<p>TRX_UNDO_UPD_EXIST_REC等等。</p>
<p>除了insert产生的undo日志中没有roll_pointer字段，其他的一般都有roll_pointer这个字段，这个字段就支撑了回滚和MVCC的功能。</p>
<p><img src="/2021/12/09/undolog/undolog.png"></p>
<h2 id="Undo-log-的管理"><a href="#Undo-log-的管理" class="headerlink" title="Undo log 的管理"></a>Undo log 的管理</h2><p>类型为FIL_PAGE_UNDO_LOG的页面，是专门用来存储undo日志的，不妨称为Undo页面。</p>
<p>一个事务写的undo日志可能在一个页面中放不下，所以MySQL使用链表来组织这些undo页面。</p>
<p>在一个事务执行过程中，最多分配4个页面链表，</p>
<p>分别是</p>
<ol>
<li>针对普通表的insert undo 链表；</li>
<li>针对普通表的update undo 链表；</li>
<li>针对临时表的insert undo 链表；</li>
<li>针对临时表的update undo 链表；</li>
</ol>
<p>每个undo页面链表都对应一个Undo Log Segment。Undo页面链表的第一个页中有一个名为Undo Log Segment Header的部分，用来存储关于这个段的信息。</p>
<p>同一个事务向一个undo链表写入的undo日志算是一个组，每个组都以一个Undo Log Header 部分开头。</p>
<h2 id="undo及redo如何记录事务"><a href="#undo及redo如何记录事务" class="headerlink" title="undo及redo如何记录事务"></a>undo及redo如何记录事务</h2><h3 id="Undo-Redo事务的简化过程"><a href="#Undo-Redo事务的简化过程" class="headerlink" title="Undo + Redo事务的简化过程"></a>Undo + Redo事务的简化过程</h3><p>假设有A、B两个数据，值分别为1,2，开始一个事务，事务的操作内容为：把1修改为3，2修改为4，那么实际的记录如下（简化）：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">A.事务开始.</span><br><span class="line">B.记录A=1到undo log.</span><br><span class="line">C.修改A=3.</span><br><span class="line">D.记录A=3到redo log.</span><br><span class="line">E.记录B=2到undo log.</span><br><span class="line">F.修改B=4.</span><br><span class="line">G.记录B=4到redo log.</span><br><span class="line">H.将redo log写入磁盘。</span><br><span class="line">I.事务提交</span><br></pre></td></tr></table></figure>

<p><strong>注意是先写 undo log，再操作，最后再写redo log</strong></p>
<h3 id="崩溃恢复"><a href="#崩溃恢复" class="headerlink" title="崩溃恢复"></a>崩溃恢复</h3><p>前面说到未提交的事务和回滚了的事务也会记录Redo Log，因此在进行恢复时,这些事务要进行特殊的的处理。有2种不同的恢复策略：</p>
<ul>
<li>进行恢复时，只重做已经提交了的事务。</li>
<li>进行恢复时，<strong>重做所有事务包括未提交的事务和回滚了的事务，然后通过Undo Log回滚那些未提交的事务</strong>。</li>
</ul>
<p>MySQL数据库InnoDB存储引擎使用了B策略, InnoDB存储引擎中的恢复机制有几个特点：</p>
<ul>
<li><p><strong>在重做Redo Log时，并不关心事务性</strong>。 恢复时，没有BEGIN，也没有COMMIT,ROLLBACK的行为。也不关心每个日志是哪个事务的。尽管事务ID等事务相关的内容会记入Redo Log，这些内容只是被当作要操作的数据的一部分。</p>
</li>
<li><p>使用B策略就<strong>必须要将Undo Log持久化</strong>，而且<strong>必须要在写Redo Log之前将对应的Undo Log写入磁盘</strong>。Undo和Redo Log的这种关联，使得持久化变得复杂起来。</p>
<p>为了降低复杂度，<strong>InnoDB将Undo Log看作数据，因此记录Undo Log的操作也会记录到redo log中</strong>。</p>
<p><strong>这样undo log就可以像数据一样缓存起来</strong>，<strong>而不用在redo log之前写入磁盘了</strong>。</p>
<p>包含Undo Log操作的Redo Log，看起来是这样的：</p>
</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">记录1: &lt;trx1, Undo log insert &lt;undo_insert …&gt;&gt; # 记录的 undo-log</span><br><span class="line">记录2: &lt;trx1, insert …&gt; # 重做日志本身</span><br><span class="line">记录3: &lt;trx2, Undo log insert &lt;undo_update …&gt;&gt;</span><br><span class="line">记录4: &lt;trx2, update …&gt;</span><br><span class="line">记录5: &lt;trx3, Undo log insert &lt;undo_delete …&gt;&gt;</span><br><span class="line">记录6: &lt;trx3, delete …&gt;</span><br></pre></td></tr></table></figure>



<p>到这里，还有一个问题没有弄清楚。既然Redo没有事务性，那岂不是会重新执行被回滚了的事务？<br>确实是这样。同时Innodb也会将事务回滚时的操作也记录到redo log中。<strong>回滚操作本质上也是对数据进行修改，因此回滚时对数据的操作也会记录到Redo Log中</strong>。</p>
<p><strong>一个回滚了的事务的Redo Log</strong>，看起来是这样的：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">记录1: &lt;trx1, Undo log insert &lt;undo_insert …&gt;&gt; # 记录的 undo-log</span><br><span class="line">记录2: &lt;trx1, insert A…&gt; # 重做日志本身</span><br><span class="line">记录3: &lt;trx1, Undo log insert &lt;undo_update …&gt;&gt;</span><br><span class="line">记录4: &lt;trx1, update B…&gt;</span><br><span class="line">记录5: &lt;trx1, Undo log insert &lt;undo_delete …&gt;&gt;</span><br><span class="line">记录6: &lt;trx1, delete C…&gt;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">下面是对应的回滚操作</span></span><br><span class="line">记录7: &lt;trx1, insert C&gt; </span><br><span class="line">记录8: &lt;trx1, update B to old value&gt;</span><br><span class="line">记录9: &lt;trx1, delete A&gt;</span><br></pre></td></tr></table></figure>


<p><strong>一个被回滚了的事务在恢复时的操作就是先redo再undo，因此不会破坏数据的一致性</strong>。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/MySQL/" rel="tag"># MySQL</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/12/09/redolog/" rel="prev" title="MySQL —— Redo log">
                  <i class="fa fa-chevron-left"></i> MySQL —— Redo log
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/12/09/Redis-%E5%93%A8%E5%85%B5/" rel="next" title="Redis-哨兵">
                  Redis-哨兵 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
